<template>
  <div class="comment-container">
    <h2>商品评价</h2>
    <!-- 发布评论表单（始终显示） -->
    <form @submit.prevent="addProductComment" class="comment-form">
      <!-- 商品ID自动填充，不允许用户修改 -->
      <input v-model.number="newComment.product_id" type="number" readonly class="readonly-input">
      <input v-model.number="newComment.user_id" type="number" min="1" placeholder="用户ID（数字）" required>
      <input v-model.number="newComment.order_id" type="number" min="1" placeholder="订单ID（必填，数字）" required />
      <input v-model="newComment.imagesInput" type="text" placeholder="图片URL（多个用逗号分隔）" />
      <input v-model.number="newComment.rating" type="number" min="1" max="5" placeholder="评分(1-5)" required />
      <textarea v-model="newComment.content" placeholder="请输入评论内容" required></textarea>
      <button type="submit">发布评论</button>
      <!-- 错误提示 -->
      <p v-if="errorMsg" class="error">{{ errorMsg }}</p>
    </form>
    <!-- 评论列表区域 -->
    <div class="comments-list-container">
      <h3>用户评论</h3>
      <ul class="comments-list" v-if="comments.length > 0">
        <li v-for="comment in comments" :key="comment.id" class="comment-item">
          <div class="comment-header">
            <div class="comment-avatar"
              :style="{ backgroundImage: `url(https://picsum.photos/seed/${comment.id}/40/40)` }"></div>
            <div class="comment-author">匿名用户</div>
          </div>
          <div class="comment-content">
            <p>评分: {{ comment.rating }}星</p>
            <p>{{ comment.content }}</p>
          </div>
          <p class="comment-time">创建时间: {{ formatDate(comment.created_at) }}</p>
          <!-- 显示评论图片 -->
          <div v-if="comment.images" class="comment-images">
            <img v-for="(img, idx) in comment.images.split(',')" :key="idx" :src="img" alt="评论图片" class="comment-img">
          </div>
          <!-- 显示评论回复 -->
          <div v-if="comment.reply_content" class="reply">
            <p>商家回复: {{ comment.reply_content }}</p>
            <p>回复时间: {{ formatDate(comment.reply_created_at || comment.created_at) }}</p>
          </div>
          <!-- 回复评论表单 - 不再使用comment.id关联回复内容 -->
          <form @submit.prevent="replyToComment(comment)" class="reply-form">
            <input v-model="comment.replyInput" type="text" placeholder="输入回复内容" required />
            <button type="submit">回复</button>
            <!-- 回复成功提示 - 直接使用评论对象的success状态 -->
            <p v-if="comment.replySuccess" class="success">回复成功！</p>
          </form>
        </li>
      </ul>
      <p v-else class="no-comments">暂无评论，快来发表第一条评论吧~</p>
    </div>
  </div>
</template>
<script setup>
import { ref, onMounted } from 'vue';
import { useRoute } from 'vue-router';
import api from '@/api/history';

const route = useRoute();
const productId = route.params.id;
const comments = ref([]);
const errorMsg = ref('');

// 评论表单数据（自动填充商品ID）
const newComment = ref({
  product_id: Number(productId), // 从路由自动获取商品ID
  user_id: null,
  order_id: null,
  imagesInput: '',
  images: '',
  rating: null,
  content: '',
  is_auto: false,
  created_at: null
});

// 格式化日期显示
const formatDate = (dateString) => {
  if (!dateString) return '';
  const date = new Date(dateString);
  return date.toLocaleString(); // 转换为本地时间格式
};

// 获取评论列表
const fetchComments = async () => {
  try {
    const response = await api.get(`/products/${productId}/comments`);
    // 为每个评论添加回复输入和成功状态属性
    comments.value = response.data.map(comment => ({
      ...comment,
      replyInput: '',      // 存储当前评论的回复内容
      replySuccess: false  // 存储当前评论的回复成功状态
    }));
  } catch (error) {
    console.error('获取商品评价失败:', error);
  }
};

// 发布评论
const addProductComment = async () => {
  errorMsg.value = '';
  try {
    // 前端验证
    if (!newComment.value.user_id) {
      errorMsg.value = '请输入用户ID';
      return;
    }
    if (!newComment.value.order_id) {
      errorMsg.value = '请输入订单ID';
      return;
    }
    if (!newComment.value.rating || newComment.value.rating < 1 || newComment.value.rating > 5) {
      errorMsg.value = '评分必须为1-5之间的数字';
      return;
    }
    if (!newComment.value.content.trim()) {
      errorMsg.value = '请输入评论内容';
      return;
    }
    // 处理数据格式
    newComment.value.created_at = new Date().toISOString();
    newComment.value.images = newComment.value.imagesInput
      ? newComment.value.imagesInput.split(',').map(url => url.trim()).filter(Boolean).join(',')
      : '';
    // 提交评论
    await api.post(`/products/${productId}/comments`, newComment.value);
    await fetchComments();
    resetCommentForm();
  } catch (error) {
    errorMsg.value = error.response?.data?.detail || '发布评论失败，请重试';
    console.error('发布评论失败:', error);
  }
};

// 回复评论 - 直接使用评论对象获取ID和回复内容
const replyToComment = async (comment) => {
  try {
    // 构建符合后端要求的请求参数，从评论对象直接获取ID
    const requestData = {
      content: comment.content,  // 关键：传递被回复评论的内容用于匹配
      reply_content: comment.replyInput  // 回复内容
    };
    // 调用后端回复接口
    await api.post(`/products/${productId}/comments/reply`, requestData);
    // 显示回复成功提示
    comment.replySuccess = true;
    // 刷新评论列表
    await fetchComments();

    // 3秒后隐藏成功提示
    setTimeout(() => {
      comment.replySuccess = false;
    }, 3000);

  } catch (error) {
    console.error('回复评论失败:', error);
    errorMsg.value = error.response?.data?.detail || '回复评论失败，请重试';
  }
};

// 重置评论表单
const resetCommentForm = () => {
  newComment.value = {
    ...newComment.value,
    user_id: null,
    order_id: null,
    imagesInput: '',
    images: '',
    rating: null,
    content: '',
    created_at: null
  };
};

onMounted(() => {
  fetchComments();
});
</script>
<style scoped>
/* 原有样式保持不变 */
.success {
  color: #42b983;
  font-size: 14px;
  margin: 5px 0 0 0;
}

.comment-container {
  padding: 15px;
}

.comment-form {
  margin: 20px 0;
  padding: 15px;
  border: 1px solid #eee;
  border-radius: 4px;
}

.comment-form input,
.comment-form textarea {
  display: block;
  margin: 10px 0;
  padding: 8px;
  width: 100%;
  box-sizing: border-box;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.readonly-input {
  background-color: #f5f5f5;
  color: #666;
}

.comment-form button {
  background-color: #ff6b00;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 4px;
  cursor: pointer;
}

.error {
  color: #e63946;
  font-size: 14px;
  margin: 5px 0 0 0;
}

.comments-list-container {
  margin-top: 30px;
}

.comments-list {
  list-style: none;
  padding: 0;
}

.comment-item {
  margin: 15px 0;
  padding: 15px;
  border: 1px solid #eee;
  border-radius: 4px;
}

.comment-author {
  font-weight: bold;
  margin-bottom: 5px;
}

.comment-content {
  margin-bottom: 10px;
}

.comment-time {
  color: #999;
  font-size: 14px;
}

.no-comments {
  color: #666;
  text-align: center;
  padding: 20px;
  background-color: #f9f9f9;
  border-radius: 4px;
}

.comment-images {
  margin: 10px 0;
  display: flex;
  gap: 10px;
}

.comment-img {
  width: 80px;
  height: 80px;
  object-fit: cover;
  border-radius: 4px;
}

.reply {
  margin: 10px 0 0 15px;
  padding: 10px;
  background-color: #f9f9f9;
  border-radius: 4px;
}

.reply-form {
  margin: 10px 0 0 15px;
  display: flex;
  gap: 10px;
}

.reply-form input {
  flex: 1;
  padding: 5px;
}

.reply-form button {
  padding: 5px 10px;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.comment-header {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 10px;
}

.comment-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background-size: cover;
  background-position: center;
}

/* 调整原有样式 */
.comment-author {
  font-weight: bold;
  margin-bottom: 0; /* 移除原有的margin-bottom */
}
</style>